package com.fiblue.imageserver.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

@RestController
@RequestMapping("/img")
public class ImageController {
    //该接口未完成，调用第二个接口即可
    @GetMapping("/get/{id}")
    public void  getImage(@PathVariable String id) throws IOException {
        String path="https://gitee.com/gui_collar/image/raw/master"+id;
        URL url =new URL(path);
        InputStream inputStream= url.openStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = bufferedInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        bufferedInputStream.close();
    }
    @GetMapping("/get2/{id}")
    public ResponseEntity<Resource> getImage2(@PathVariable String id) throws IOException {
        String path="https://gitee.com/gui_collar/image/raw/master/"+id;
        Resource resource = new UrlResource(path);
        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity
                    .ok()
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    }

